#Requires AutoHotkey v2.0

global ToLang := "zh"

ToLangMap := Map(
"中文zh",	"zh",
"英语en",	"en",
"粤语yue",	"yue",
"文言文wyw",	"wyw",
"日语jp",	"jp",
"韩语kor",	"kor",
"法语fra",	"fra",
"西班牙语spa",	"spa",
"泰语th",	"th",	
"阿拉伯语ara",	"ara",	
"俄语ru",	"ru",
"葡萄牙语pt",	"pt",
"德语de",	"de",	
"意大利语it",	"it",
"希腊语el",	"el",
"荷兰语nl",	"nl",
"波兰语pl",	"pl",
"保加利亚语bul",	"bul",
"爱沙尼亚语est",	"est",	
"丹麦语dan",	"dan",
"芬兰语fin",	"fin",
"捷克语cs",	"cs",	
"罗马尼亚语rom",	"rom",
"斯洛文尼亚语slo",	"slo",	
"瑞典语swe",	"swe",	
"匈牙利语hu",	"hu",
"繁体中文cht",	"cht",	
"越南语vie",	"vie",
)

switchToLang(lang) {
  global ToLang := OnlyInput.switchParameter(ToLangMap, lang)
}

Translate(query, to_lang:=ToLang) {
  from_lang := "auto"
  u8query := StrGet(OnlyInput.StrBuf(query, "UTF-8").Ptr, "cp0")
 
  appid := BaiduTrId  ;你的百度翻译账号
  key := BaiduTrKey    ;你的百度翻译密码
  salt := A_Mon . A_MDay . A_Hour . A_Min . A_Sec
  sign := MD5(appid . u8query . salt . key)
  query := OnlyInput.urlEncode(query)
  
  url := "http://fanyi-api.baidu.com/api/trans/vip/translate"
         . "?q="      . query 
         . "&from="   . from_lang 
         . "&to="     . to_lang 
         . "&appid="  . appid 
         . "&salt="   . salt 
         . "&sign="   . sign            ;请求地址
  whr := ComObject("WinHttp.WinHttpRequest.5.1")  ;调用Windows COM组件
  whr.Open("GET", url, true)
  whr.SetTimeouts(0, 60000, 30000, 1000)
  whr.Send()
  try {
    whr.WaitForResponse()
    obj := JSON2.parse(whr.ResponseText)
  } catch {
    obj := {error_code: whr.ResponseText}
  }
  if (HasProp(obj, "error_code")) {
    res := obj.error_code
  } else {
    res := ((obj.trans_result)[1]).dst 
  }
  return res
}

